package com.terrace.web.tagext.easyui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.terrace.core.common.model.UserInfo;
import com.terrace.db.system.mapper.entity.Permission;
import com.terrace.db.system.service.PermissionService;
import com.terrace.web.constant.GlobalsConstant;
import com.terrace.web.constant.IconConstant;

/**
 * 导航菜单标签
 * 
 * @author jiangyg
 *
 */
public class MenuTag extends TagSupport {

	private static final long serialVersionUID = -1465902789380224017L;

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(MenuTag.class);

	/**
	 * 导航菜单样式
	 */
	private String style = "easyui";
	
	@Override
	public int doStartTag() throws JspException {
		return EVAL_PAGE;
	}

	@Override
	public int doEndTag() throws JspException {
		try {
			JspWriter out = this.pageContext.getOut();
			StringBuffer sb = new StringBuffer();
			
			// 导航集合--key：导航ID 	value：导航信息
			List<Permission> navList = new ArrayList<Permission>();
			// 菜单集合--key：导航ID	value：菜单信息列表
			Map<String, List<Permission>> menuList = new HashMap<String, List<Permission>>();
			
			UserInfo user = (UserInfo) this.pageContext.getSession().getAttribute(GlobalsConstant.USER_SESSION_KEY);
			WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(this.pageContext.getServletContext());
			PermissionService permissionService = wac.getBean(PermissionService.class);
			List<Permission> permiList = permissionService.selectVisitMenuByUserId(user.getUserId());
			for (Permission permi : permiList) {
				if (StringUtils.isBlank(permi.getParentPermiId())) {
					navList.add(permi);
				}
				if (StringUtils.isNotBlank(permi.getParentPermiId())) {
					List<Permission> permis = menuList.get(permi.getParentPermiId());
					if (permis == null) {
						permis = new ArrayList<Permission>();
					}
					permis.add(permi);
					menuList.put(permi.getParentPermiId(), permis);
				}
			}
			
			// 生成导航菜单标签
			Iterator<Permission> iterator = navList.iterator();
			while (iterator.hasNext()) {
				// 生成导航
				Permission navPermi = iterator.next();
				sb.append("<div title=\"" + navPermi.getPermiName() + "\" "
						+ "style=\"padding: 5px;\" data-options=\"border:false,iconCls:'"
						+ IconConstant.obtainIconClass(navPermi.getPermiIcon()) + "'\"><div>");
				// 生成菜单
				List<Permission> menus = menuList.get(navPermi.getId());
				if (menus != null) {
					for (Permission menuPermi : menus) {
						sb.append("<a id=\"" + menuPermi.getId() + "\" name=\"accordion-nav-a\" "
								+ "title=\"" + menuPermi.getPermiName() + "\" icon=\"" + IconConstant.obtainIconClass(menuPermi.getPermiIcon())
								+ "\" class=\"easyui-linkbutton\" data-options=\"plain:true,iconCls:'"
								+ IconConstant.obtainIconClass(menuPermi.getPermiIcon()) + "'\" src=\"" + menuPermi.getPermiUrl()
								+ "\" style=\"width:98%;margin-bottom:5px;\">" + menuPermi.getPermiName() + "</a>");
					}
				}
				sb.append("</div></div>");
			}
			
			out.print(sb.toString());
		} catch (Exception e) {
			logger.error("生成导航菜单标签出错：", e);
		}
		return EVAL_PAGE;
	}
	
	public String getStyle() {
		return style;
	}

	public void setStyle(String style) {
		this.style = style;
	}

	/**
	public static void createAccordionNav(final StringBuffer sb, List<Permission> menus, String parentPermiId) {
		for (Permission permission : menus) {
			if (StringUtils.equals(parentPermiId, permission.getParentPermiId())) {
//				sb.append(permission.getId());
				sb.append("<div title=\"" + permission.getPermiName() + "\" " + "style=\"padding: 5px;\" data-options=\"border:false,iconCls:'" + permission.getPermiIcon() + "'\"><div>");
				
				createAccordionNav(sb, menus, permission.getId());
			}
		}
	}
	**/
	
	/**
	public static void main(String[] args) {
		List<Permission> list = new ArrayList<Permission>();
		String pid = null;
		for (int i = 0; i < 10; i++) {
			Permission permi = new Permission();
			permi.setId("id_" + i);
			permi.setPermiName("permiName_" + i);
			permi.setParentPermiId(pid);
			if (i % 2 == 0) {
				pid = "id_" + i;
			}
			list.add(permi);
		}
		System.out.println(JsonUtils.beanToJson(list));
		StringBuffer sb = new StringBuffer();
		createAccordionNav(sb, list, null);
		System.out.println(sb.toString());
		
	}
	**/

}
